package sql

import (
	"fmt"
	"more_ssh/conf"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

func Init() error {
	db, err := gorm.Open(sqlite.Open("my.db"), &gorm.Config{})

	if err != nil {
		fmt.Println(err)
		return err
	}

	// 检测表是否存在
	ok := db.Migrator().HasTable(&User{})
	if !ok {
		fmt.Println("未检测到user表")
	}

	db.AutoMigrate(&User{})
	db.AutoMigrate(&Host{})
	db.AutoMigrate(&Account{})
	db.AutoMigrate(&Audit{})

	user := User{}

	tx := db.Where("user = ?", "admin").First(&user)

	if tx.Error != nil {
		fmt.Println("未检测到admin账号，进行数据初始化")
		admin := &User{
			User:     "admin",
			Name:     "admin",
			Password: "admin",
			Email:    "moujunmore@qq.com",
			Phone:    "13333333333",
			Status:   true,
			Role:     1}

		db.Create(admin)
	}
	conf.DB = db
	return nil
}
